use crate::solution::Solution;

impl Solution {
    pub fn num_subarray_bounded_max(nums: Vec<i32>, left: i32, right: i32) -> i32 {
        let mut l = 0;
        let mut e = 0;
        let mut ind = 0;
        let mut ans = 0;
        while ind < nums.len() && ind < nums.len() {
            if nums[ind] < left {
                l += 1;
                ind += 1
            } else if nums[ind] <= right {
                e = 1;
                ind += 1;
                while ind < nums.len() && nums[ind] >= left && nums[ind] <= right {
                    e += 1;
                    ind += 1
                }

                ans += ((1i64 + e as i64) * e as i64 / 2i64) as i32;
                ans += l * e;

                let mut l2 = 0;
                while ind < nums.len() && nums[ind] < left {
                    l2 += 1;
                    ind += 1;
                }
                ans += l2 * e;
                ans += l * l2;
                l += l2;
                l += e;
            } else {
                l = 0;
                ind += 1;
            }
        }
        ans
    }
}
